﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using HtmlAgilityPack;
using System.Collections.ObjectModel;
using OnlineVideos.Entities;
using Common.Library;
using InsertIntoDataBase;
using System.Threading.Tasks;
using System.Globalization;

namespace OnlineMovies.Views
{
    public class BowlerDetails
    {
        public string InningsHead
        {
            get;
            set;
        }
        public int PlayerID
        {
            get;
            set;
        }
        public string PlayerName
        {
            get;
            set;
        }
        public double Overs
        {
            get;
            set;
        }
        public int Runs
        {
            get;
            set;
        }
        public int Maidens
        {
            get;
            set;
        }
        public int Wickets
        {
            get;
            set;
        }
    }
    public class PlayerDetails
    {
        public string InningsHead
        {
            get;
            set;
        }
        public int PlayerID
        {
            get;
            set;
        }
        public string PlayerName
        {
            get;
            set;
        }
        public string PlayerStatus
        {
            get;
            set;
        }
        public int Runs
        {
            get;
            set;
        }
        public int Overs
        {
            get;
            set;
        }
        public string TeamExtras
        {
            get;
            set;
        }
        public string TeamTotal
        {
            get;
            set;
        }
    }
    public class MatchDetails
    {
        public int MatchID
        {
            get;
            set;
        }
        public string MatchTitle
        {
            get;
            set;
        }
        public string MatchType
        {
            get;
            set;
        }
        public string MatchDate
        {
            get;
            set;
        }
        public string MatchUrl
        {
            get;
            set;
        }
        public string MatchResult
        {
            get;
            set;
        }

    }
    public partial class AddMatchScore : PhoneApplicationPage
    {
        IDictionary<string, string> DicForPlayernames = new Dictionary<string, string>();
        IDictionary<string, int> Dic = new Dictionary<string, int>();
        private static bool IsDataLoaded;
        static string matchurl = string.Empty;
        static string matchresult = string.Empty;
        static string teamBinnings = string.Empty;
        static string teamAinnings = string.Empty;
        public static IDictionary<string, string> matchdic = new Dictionary<string, string>();
        public static IDictionary<string, string> categorydic = new Dictionary<string, string>();
        public static ObservableCollection<MatchDetails> MatchList = default(ObservableCollection<MatchDetails>);
        public static ObservableCollection<PlayerDetails> PlayerList = default(ObservableCollection<PlayerDetails>);
        public static ObservableCollection<BowlerDetails> BowlerList = default(ObservableCollection<BowlerDetails>);
        public static ObservableCollection<PlayerDetails> PlayerList1 = default(ObservableCollection<PlayerDetails>);
        public static ObservableCollection<BowlerDetails> BowlerList1 = default(ObservableCollection<BowlerDetails>);
        public AddMatchScore()
        {
            InitializeComponent();
            IsDataLoaded = false;
            Loaded += AddMatchScore_Loaded;
        }

        void AddMatchScore_Loaded(object sender, RoutedEventArgs e)
        {
            if (IsDataLoaded == false)
            {
                CategoryList.SelectionChanged += CtaegoryList_SelectionChanged_1;
                List<string> catlist = new List<string>();
                categorydic.Clear();

                categorydic.Add("Recent Results", "http://www.espncricinfo.com/ci/engine/current/match/scores/recent.html?days=7");
                categorydic.Add("Current 2013 season", "http://www.espncricinfo.com/ci/engine/series/index.html?season=2013");
                categorydic.Add("2012-13 season", "http://www.espncricinfo.com/ci/engine/series/index.html?season=2012%2F13");
                categorydic.Add("2012 season", "http://www.espncricinfo.com/ci/engine/series/index.html?season=2012");
                categorydic.Add("2014 season", "http://www.espncricinfo.com/ci/engine/series/index.html?season=2014");
                categorydic.Add("2013-14 season", "http://www.espncricinfo.com/ci/engine/series/index.html?season=2013%2F14");
                foreach (KeyValuePair<string, string> k in categorydic)
                {
                    catlist.Add(k.Key);

                }
                CategoryList.ItemsSource = catlist;

                CategoryList.SelectedIndex = 0;
                IsDataLoaded = true;
            }
        }
        private void GetAllMatches(string Url)
        {
            if(NetworkHelper.IsNetworkAvailableForDownloads())
            LoadMatches(Url);
        }
        private void LoadMatches(string url)
        {
            MatchList = new ObservableCollection<MatchDetails>();
            string PageUrl = string.Empty;
            PageUrl = url;
            WebClient client = new WebClient();
            client.Headers[HttpRequestHeader.UserAgent] = "Mozilla/5.0 (Windows; U; Windows NT 6.1; de; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12";
            client.DownloadStringAsync(new Uri(PageUrl));
            client.DownloadStringCompleted += client_DownloadStringCompleted;

        }

        void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            string pagehtml = e.Result.ToString();
            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(pagehtml);

            List<string> MatchTitleList = new List<string>();
            List<string> MatchTypeList = new List<string>();
            List<string> MatchDateList = new List<string>();
            List<string> MatchUrlList = new List<string>();
            List<string> MatchResultList = new List<string>();

            if (CategoryList.SelectedIndex > 0)
            {
                MatchTitleList = doc.DocumentNode.SelectNodes("//a[@class='potMatchLink']").Select(i => HttpUtility.HtmlDecode(i.InnerText)).ToList();
                MatchTypeList = doc.DocumentNode.SelectNodes("//p[@class='potMatchHeading']").Select(i => HttpUtility.HtmlDecode(i.InnerText.Substring(0, i.InnerText.IndexOf('-')))).ToList();
                MatchDateList = doc.DocumentNode.SelectNodes("//p[@class='potMatchHeading']").Select(i => HttpUtility.HtmlDecode(i.InnerText.Substring(i.InnerText.LastIndexOf('-') + 1))).ToList();
                MatchUrlList = doc.DocumentNode.SelectNodes("//span [@class='potMatchLink']/a").Select(i => i.Attributes.Where(j => j.Name == "href").FirstOrDefault().Value.ToString()).ToList();
                MatchResultList = doc.DocumentNode.SelectNodes("//p[@class='potMatchHeading']").Select(i => HttpUtility.HtmlDecode(i.SelectSingleNode("following::p[@class='potMatchText mat_status']").InnerText)).ToList();
                //List<string> urllist = doc.DocumentNode.SelectNodes("//a[@class='wallpaperbrowsultext']").Select(i => HttpUtility.HtmlDecode(i.InnerText)).ToList();
                //foreach (string url in urllist)
                //{
                //    WebClient client2 = new WebClient();
                //    client2.Headers[HttpRequestHeader.UserAgent] = "Mozilla/5.0 (Windows; U; Windows NT 6.1; de; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12";
                //    client2.DownloadStringAsync(new Uri(url));
                //    client2.DownloadStringCompleted += client2_DownloadStringCompleted;
                //}

            }
            else
            {
                MatchTitleList = doc.DocumentNode.SelectNodes("//a[@class='potMatchLink']").Where(i => i.ParentNode.PreviousSibling.ParentNode.InnerText.Contains("ODI") || i.ParentNode.PreviousSibling.ParentNode.InnerText.Contains("T20")).Select(i => HttpUtility.HtmlDecode(i.InnerText)).ToList();
                if (MatchTitleList.Count == 0)
                {
                    MatchTitleList = doc.DocumentNode.SelectNodes("//a[@class='potMatchLink']").Select(i => HttpUtility.HtmlDecode(i.InnerText)).ToList();
                    MatchTypeList = doc.DocumentNode.SelectNodes("//p[@class='potMatchHeading']").Select(i => HttpUtility.HtmlDecode(i.InnerText.Substring(0, i.InnerText.IndexOf('-')))).ToList();
                    MatchDateList = doc.DocumentNode.SelectNodes("//p[@class='potMatchHeading']").Select(i => HttpUtility.HtmlDecode(i.InnerText.Substring(i.InnerText.LastIndexOf('-') + 1))).ToList();
                    MatchUrlList = doc.DocumentNode.SelectNodes("//span [@class='potMatchLink']/a").Select(i => i.Attributes.Where(j => j.Name == "href").FirstOrDefault().Value.ToString()).ToList();
                    MatchResultList = doc.DocumentNode.SelectNodes("//p[@class='potMatchHeading']").Select(i => HttpUtility.HtmlDecode(i.SelectSingleNode("following::p[@class='potMatchText mat_status']").InnerText)).ToList();
                }
                else
                {
                    MatchTypeList = doc.DocumentNode.SelectNodes("//p[@class='potMatchHeading']").Where(i => i.InnerText.Contains("ODI") || i.InnerText.Contains("T20")).Select(i => HttpUtility.HtmlDecode(i.InnerText.Substring(0, i.InnerText.IndexOf('-')))).ToList();
                    MatchDateList = doc.DocumentNode.SelectNodes("//p[@class='potMatchHeading']").Where(i => i.InnerText.Contains("ODI") || i.InnerText.Contains("T20")).Select(i => HttpUtility.HtmlDecode(i.InnerText.Substring(i.InnerText.LastIndexOf('-') + 1))).ToList();
                    MatchUrlList = doc.DocumentNode.SelectNodes("//span [@class='potMatchLink']/a").Where(i => i.ParentNode.PreviousSibling.ParentNode.InnerText.Contains("ODI") || i.ParentNode.PreviousSibling.ParentNode.InnerText.Contains("T20")).Select(i => i.Attributes.Where(j => j.Name == "href").FirstOrDefault().Value.ToString()).ToList();
                    MatchResultList = doc.DocumentNode.SelectNodes("//p[@class='potMatchHeading']").Where(i => i.InnerText.Contains("ODI") || i.InnerText.Contains("T20")).Select(i => HttpUtility.HtmlDecode(i.SelectSingleNode("following::p[@class='potMatchText mat_status']").InnerText)).ToList();
                }
            
            }

            for (int i = 0; i < MatchTitleList.Count; i++)
            {
                MatchDetails md = new MatchDetails();
                md.MatchID = MatchList.Count + 1;
                md.MatchTitle = MatchTitleList[i].Trim();
                md.MatchType = MatchTypeList[i];
                md.MatchDate = MatchDateList[i];
                md.MatchUrl = "http://www.espncricinfo.com" + MatchUrlList[i];
                md.MatchResult = MatchResultList[i];

                MatchList.Add(md);
            }
            if (MatchList.Count > 0)
            {
                NameList.Items.Clear();
                foreach (MatchDetails k in MatchList)
                {

                    NameList.Items.Add(k.MatchTitle + "@" + k.MatchDate.Trim());
                }
            }

        }

        void client2_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            string html = e.Result.ToString();
            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(html);
            List<string> MatchTitleList = new List<string>();
            List<string> MatchTypeList = new List<string>();
            List<string> MatchDateList = new List<string>();
            List<string> MatchUrlList = new List<string>();
            List<string> MatchResultList = new List<string>();
            MatchTitleList = doc.DocumentNode.SelectNodes("//a[@class='potMatchLink']").Select(i => HttpUtility.HtmlDecode(i.InnerText)).ToList();
            MatchTypeList = doc.DocumentNode.SelectNodes("//p[@class='potMatchHeading']").Select(i => HttpUtility.HtmlDecode(i.InnerText.Substring(0, i.InnerText.IndexOf('-')))).ToList();
            MatchDateList = doc.DocumentNode.SelectNodes("//p[@class='potMatchHeading']").Select(i => HttpUtility.HtmlDecode(i.InnerText.Substring(i.InnerText.LastIndexOf('-') + 1))).ToList();
            MatchUrlList = doc.DocumentNode.SelectNodes("//span [@class='potMatchLink']/a").Select(i => i.Attributes.Where(j => j.Name == "href").FirstOrDefault().Value.ToString()).ToList();
            MatchResultList = doc.DocumentNode.SelectNodes("//p[@class='potMatchHeading']").Select(i => HttpUtility.HtmlDecode(i.SelectSingleNode("following::p[@class='potMatchText mat_status']").InnerText)).ToList();
        }

        private void CtaegoryList_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
        {
            if (CategoryList.SelectedIndex != -1)
            {
                TypeList.Items.Clear();
                MatchsList.Items.Clear();
                if (CategoryList.SelectedIndex > 0)
                {
                    TypeList.Items.Add("One-Day Internationals");
                    TypeList.Items.Add("Twenty20 Internationals");
                }
                else
                    GetAllMatches(categorydic.Where(i => i.Key == CategoryList.SelectedItem.ToString()).FirstOrDefault().Value);
            }
        }
        private void GetSection(HtmlDocument helpDocument, string SectionName)
        {
            WebClient webc = new WebClient();
            webc.DownloadStringAsync(new Uri(categorydic.Where(i => i.Key == CategoryList.SelectedItem.ToString()).FirstOrDefault().Value), SectionName);
            webc.DownloadStringCompleted += webc_DownloadStringCompleted;


        }
        void webc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            string html = e.Result;
            string sectionname = e.UserState.ToString();
            HtmlDocument helpDocument = new HtmlDocument();
            helpDocument.LoadHtml(html);
            List<HtmlNode> NodeList = new List<HtmlNode>();
            matchdic = new Dictionary<string, string>();
            MatchsList.Items.Clear();
            NodeList = Getsibling(helpDocument, sectionname);
            foreach (HtmlNode node in NodeList)
            {
                matchdic.Add("http://www.espncricinfo.com" + node.NextSibling.Descendants().Where(i => i.Name == "a").FirstOrDefault().Attributes.Where(j => j.Name == "href").FirstOrDefault().Value, node.NextSibling.Descendants().Where(i => i.Name == "a").FirstOrDefault().InnerText);
                MatchsList.Items.Add(node.NextSibling.Descendants().Where(i => i.Name == "a").FirstOrDefault().InnerText);

            }

        }
        public List<HtmlNode> Getsibling(HtmlDocument helpDocument, string SectionName)
        {
            HtmlNode startNode = helpDocument.DocumentNode.Descendants("p").Where(d => d.InnerText.Equals(SectionName, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
            if (startNode == null)
                return null;

            List<HtmlNode> section = new List<HtmlNode>();
            HtmlNode sibling = startNode.NextSibling;

            while (sibling != null && sibling.NextSibling.OuterHtml.Contains("<dl"))
            {
                section.Add(sibling);
                sibling = sibling.NextSibling;
            }

            return section;
        }
        private void TypeList_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
        {
            if (TypeList.SelectedIndex != -1)
            {
                List<HtmlNode> NodeList = new List<HtmlNode>();
                matchdic = new Dictionary<string, string>();
                MatchsList.Items.Clear();
                if(NetworkHelper.IsNetworkAvailableForDownloads())
                GetSection(default(HtmlDocument), TypeList.SelectedItem.ToString());
            }

        }
        private void MatchsList_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
        {
            if (MatchsList.SelectedIndex != -1)
            {
                GetAllMatches(matchdic.Where(i => i.Value == MatchsList.SelectedItem.ToString()).FirstOrDefault().Key);
            }
        }
        private void NameList_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
        {
            if (NameList.SelectedIndex != -1)
            {
                if (NameList.SelectedItem != null)
                {
                    string[] arr = new string[2];
                    arr = NameList.SelectedItem.ToString().Split('@');
                    matchurl = MatchList.Where(i => i.MatchTitle == arr[0]).FirstOrDefault().MatchUrl;
                    matchresult = MatchList.Where(i => i.MatchTitle == arr[0]).FirstOrDefault().MatchResult;
                }
            }
        }
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            getdatabtn.IsEnabled = false;
            if (!string.IsNullOrEmpty(matchurl))
            {
                WebClient client1 = new WebClient();
                client1.Headers[HttpRequestHeader.UserAgent] = "Mozilla/5.0 (Windows; U; Windows NT 6.1; de; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12";
                client1.DownloadStringAsync(new Uri(matchurl));
                client1.DownloadStringCompleted += client1_DownloadStringCompleted;
            }
        }

        void client1_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
                if (e.Error == null)
                {
                    string pagehtml = e.Result.ToString();
                    HtmlDocument doc = new HtmlDocument();
                    doc.LoadHtml(pagehtml);

                    PlayerList = new ObservableCollection<PlayerDetails>();
                    List<string> PlayerNamesList = new List<string>();
                    List<string> PlayerStatusList = new List<string>();
                    List<string> PlayersRunsList = new List<string>();
                    List<string> PlayerBallsList = new List<string>();
                    List<string> PlayersDidNotBat = new List<string>();
                    PlayerNamesList = doc.DocumentNode.SelectNodes("//table [@id='inningsBat1'and @class='inningsTable']/tr[@class='inningsRow']/td[@class='playerName']").Select(i => i.InnerText).ToList();
                    PlayerStatusList = doc.DocumentNode.SelectNodes("//table [@id='inningsBat1'and @class='inningsTable']/tr[@class='inningsRow']/td[@class='battingDismissal']").Select(i => i.InnerText).ToList();
                    PlayersRunsList = doc.DocumentNode.SelectNodes("//table [@id='inningsBat1'and @class='inningsTable']/tr[@class='inningsRow']/td[@class='battingRuns']").Select(i => i.InnerText).ToList();
                    PlayerBallsList = doc.DocumentNode.SelectNodes("//table [@id='inningsBat1'and @class='inningsTable']/tr[@class='inningsRow']/td[@class='battingDetails'][2]").Select(i => i.InnerText).ToList();

                    for (int c = 0; c < PlayerNamesList.Count; c++)
                    {
                        PlayerDetails pd = new PlayerDetails();
                        if (c == 0)
                            pd.InningsHead = doc.DocumentNode.SelectSingleNode("//table [@id='inningsBat1'and @class='inningsTable']/tr[@class='inningsHead']/td[2]").InnerText;
                        pd.PlayerID = PlayerList.Count + 1;
                        pd.PlayerName = PlayerNamesList[c].ToString();
                        pd.PlayerStatus = PlayerStatusList[c].ToString();
                        pd.Runs = Convert.ToInt32(PlayersRunsList[c].ToString());
                        pd.Overs = Convert.ToInt32(PlayerBallsList[c].ToString());
                        pd.TeamExtras = doc.DocumentNode.SelectNodes("//table [@id='inningsBat1'and @class='inningsTable']/tr[@class='inningsRow']").Elements().Where(f => f.Name == "td" && f.Attributes.Where(j => j.Value == "inningsDetails").FirstOrDefault() != null && f.InnerText == "Extras").FirstOrDefault().NextSibling.NextSibling.InnerText;
                        string Check = doc.DocumentNode.SelectNodes("//table [@id='inningsBat1'and @class='inningsTable']/tr[@class='inningsRow']").Elements().Where(f => f.Name == "td" && f.Attributes.Where(j => j.Value == "inningsDetails").FirstOrDefault() != null && f.InnerText == "Total").FirstOrDefault().NextSibling.NextSibling.InnerText;
                        string overs = string.Empty;
                        string wickets = string.Empty;
                        if (!Check.Substring(0, Check.IndexOf(';')).Contains("all out"))
                        {
                            wickets = Check.Substring(1, Check.IndexOf(';')).Substring(0, Check.Substring(1, Check.IndexOf(';')).IndexOf("wickets"));
                            overs = Check.Substring(Check.IndexOf(';') + 1, (Check.IndexOf("overs") - (Check.IndexOf(';') + 1)) - 1);
                        }
                        else
                        {
                            wickets = "";
                            overs = Check.Substring(Check.IndexOf(';') + 1, (Check.IndexOf("overs") - (Check.IndexOf(';') + 1)) - 1);
                        }
                        if (!string.IsNullOrEmpty(wickets))
                            pd.TeamTotal = doc.DocumentNode.SelectNodes("//table [@id='inningsBat1'and @class='inningsTable']/tr[@class='inningsRow']").Elements().Where(f => f.Name == "td" && f.Attributes.Where(j => j.Value == "inningsDetails").FirstOrDefault() != null && f.InnerText == "Total").FirstOrDefault().NextSibling.NextSibling.NextSibling.NextSibling.InnerText + "/" + wickets + "(" + overs + ")";
                        else
                            pd.TeamTotal = doc.DocumentNode.SelectNodes("//table [@id='inningsBat1'and @class='inningsTable']/tr[@class='inningsRow']").Elements().Where(f => f.Name == "td" && f.Attributes.Where(j => j.Value == "inningsDetails").FirstOrDefault() != null && f.InnerText == "Total").FirstOrDefault().NextSibling.NextSibling.NextSibling.NextSibling.InnerText + "(" + overs + ")";
                        if (!PlayerList.Contains(pd))
                            PlayerList.Add(pd);
                    }
                    var Listofnodes = doc.DocumentNode.SelectNodes("//table [@id='inningsBat1'and @class='inningsTable']/following::table[1]/tr/td[1]").Where(p => p.Attributes.Where(l => l.Name == "class" && l.Value == "inningsDetails").FirstOrDefault() != null).Select(m => m).Where(f => f.InnerText.Contains("Did not bat"));
                    foreach (HtmlNode node in Listofnodes)
                    {
                        foreach (string player in node.InnerText.Substring(node.InnerText.IndexOf("Did not bat") + ("Did not bat".Length)).Split(new string[] { ",\n" }, StringSplitOptions.None))
                        {
                            PlayersDidNotBat.Add(HttpUtility.HtmlDecode(player));
                        }
                    }
                    foreach (string player in PlayersDidNotBat)
                    {
                        PlayerDetails pd = new PlayerDetails();
                        pd.PlayerID = PlayerList.Count + 1;
                        pd.PlayerName = player;
                        pd.PlayerStatus = "Did not bat";
                        pd.Runs = 0;
                        pd.Overs = 0;
                        pd.TeamExtras = doc.DocumentNode.SelectNodes("//table [@id='inningsBat1'and @class='inningsTable']/tr[@class='inningsRow']").Elements().Where(f => f.Name == "td" && f.Attributes.Where(j => j.Value == "inningsDetails").FirstOrDefault() != null && f.InnerText == "Extras").FirstOrDefault().NextSibling.NextSibling.InnerText;
                        string Check = doc.DocumentNode.SelectNodes("//table [@id='inningsBat1'and @class='inningsTable']/tr[@class='inningsRow']").Elements().Where(f => f.Name == "td" && f.Attributes.Where(j => j.Value == "inningsDetails").FirstOrDefault() != null && f.InnerText == "Total").FirstOrDefault().NextSibling.NextSibling.InnerText;
                        string overs = string.Empty;
                        string wickets = string.Empty;
                        if (!Check.Substring(0, Check.IndexOf(';')).Contains("all out"))
                        {
                            wickets = Check.Substring(1, Check.IndexOf(';')).Substring(0, Check.Substring(1, Check.IndexOf(';')).IndexOf("wickets"));
                            overs = Check.Substring(Check.IndexOf(';') + 1, (Check.IndexOf("overs") - (Check.IndexOf(';') + 1)) - 1);
                        }
                        else
                        {
                            wickets = "";
                            overs = Check.Substring(Check.IndexOf(';') + 1, (Check.IndexOf("overs") - (Check.IndexOf(';') + 1)) - 1);
                        }
                        if (!string.IsNullOrEmpty(wickets))
                            pd.TeamTotal = doc.DocumentNode.SelectNodes("//table [@id='inningsBat1'and @class='inningsTable']/tr[@class='inningsRow']").Elements().Where(f => f.Name == "td" && f.Attributes.Where(j => j.Value == "inningsDetails").FirstOrDefault() != null && f.InnerText == "Total").FirstOrDefault().NextSibling.NextSibling.NextSibling.NextSibling.InnerText + "/" + wickets + "(" + overs + ")";
                        else
                            pd.TeamTotal = doc.DocumentNode.SelectNodes("//table [@id='inningsBat1'and @class='inningsTable']/tr[@class='inningsRow']").Elements().Where(f => f.Name == "td" && f.Attributes.Where(j => j.Value == "inningsDetails").FirstOrDefault() != null && f.InnerText == "Total").FirstOrDefault().NextSibling.NextSibling.NextSibling.NextSibling.InnerText + "(" + overs + ")";
                        if (!PlayerList.Contains(pd))
                            PlayerList.Add(pd);
                    }

                    teamAinnings = doc.DocumentNode.SelectSingleNode("//table [@id='inningsBat1'and @class='inningsTable']/tr[@class='inningsHead']/td[2]").InnerText;
                    teamAinnings = teamAinnings.Substring(0, teamAinnings.IndexOf("innings") - 1).Trim();
                    foreach (PlayerDetails ss in PlayerList.ToList())
                    {
                        if (!DicForPlayernames.ContainsKey(ss.PlayerName))
                            DicForPlayernames.Add(ss.PlayerName, teamAinnings);
                    }
                    PlayerList1 = new ObservableCollection<PlayerDetails>();

                    List<string> PlayerNamesList1 = new List<string>();
                    List<string> PlayerStatusList1 = new List<string>();
                    List<string> PlayersRunsList1 = new List<string>();
                    List<string> PlayerBallsList1 = new List<string>();
                    List<string> PlayersDidNotBat1 = new List<string>();
                    PlayerNamesList1 = doc.DocumentNode.SelectNodes("//table [@id='inningsBat2'and @class='inningsTable']/tr[@class='inningsRow']/td[@class='playerName']").Select(i => i.InnerText).ToList();
                    PlayerStatusList1 = doc.DocumentNode.SelectNodes("//table [@id='inningsBat2'and @class='inningsTable']/tr[@class='inningsRow']/td[@class='battingDismissal']").Select(i => i.InnerText).ToList();
                    PlayersRunsList1 = doc.DocumentNode.SelectNodes("//table [@id='inningsBat2'and @class='inningsTable']/tr[@class='inningsRow']/td[@class='battingRuns']").Select(i => i.InnerText).ToList();
                    PlayerBallsList1 = doc.DocumentNode.SelectNodes("//table [@id='inningsBat2'and @class='inningsTable']/tr[@class='inningsRow']/td[@class='battingDetails'][2]").Select(i => i.InnerText).ToList();
                    for (int c = 0; c < PlayerNamesList1.Count; c++)
                    {
                        PlayerDetails pd = new PlayerDetails();
                        if (c == 0)
                            pd.InningsHead = doc.DocumentNode.SelectSingleNode("//table [@id='inningsBat2'and @class='inningsTable']/tr[@class='inningsHead']/td[2]").InnerText;
                        pd.PlayerID = PlayerList1.Count + 1;
                        pd.PlayerName = PlayerNamesList1[c].ToString();
                        pd.PlayerStatus = PlayerStatusList1[c].ToString();
                        pd.Runs = Convert.ToInt32(PlayersRunsList1[c].ToString());
                        pd.Overs = Convert.ToInt32(PlayerBallsList1[c].ToString());
                        pd.TeamExtras = doc.DocumentNode.SelectNodes("//table [@id='inningsBat2'and @class='inningsTable']/tr[@class='inningsRow']").Elements().Where(f => f.Name == "td" && f.Attributes.Where(j => j.Value == "inningsDetails").FirstOrDefault() != null && f.InnerText == "Extras").FirstOrDefault().NextSibling.NextSibling.InnerText;
                        string Check = doc.DocumentNode.SelectNodes("//table [@id='inningsBat2'and @class='inningsTable']/tr[@class='inningsRow']").Elements().Where(f => f.Name == "td" && f.Attributes.Where(j => j.Value == "inningsDetails").FirstOrDefault() != null && f.InnerText == "Total").FirstOrDefault().NextSibling.NextSibling.InnerText;
                        string overs = string.Empty;
                        string wickets = string.Empty;
                        if (!Check.Substring(0, Check.IndexOf(';')).Contains("all out"))
                        {
                            wickets = Check.Substring(1, Check.IndexOf(';')).Substring(0, Check.Substring(1, Check.IndexOf(';')).IndexOf("wickets"));
                            overs = Check.Substring(Check.IndexOf(';') + 1, (Check.IndexOf("overs") - (Check.IndexOf(';') + 1)) - 1);
                        }
                        else
                        {
                            wickets = "";
                            overs = Check.Substring(Check.IndexOf(';') + 1, (Check.IndexOf("overs") - (Check.IndexOf(';') + 1)) - 1);
                        }
                        if (!string.IsNullOrEmpty(wickets))
                            pd.TeamTotal = doc.DocumentNode.SelectNodes("//table [@id='inningsBat2'and @class='inningsTable']/tr[@class='inningsRow']").Elements().Where(f => f.Name == "td" && f.Attributes.Where(j => j.Value == "inningsDetails").FirstOrDefault() != null && f.InnerText == "Total").FirstOrDefault().NextSibling.NextSibling.NextSibling.NextSibling.InnerText + "/" + wickets + "(" + overs + ")";
                        else
                            pd.TeamTotal = doc.DocumentNode.SelectNodes("//table [@id='inningsBat2'and @class='inningsTable']/tr[@class='inningsRow']").Elements().Where(f => f.Name == "td" && f.Attributes.Where(j => j.Value == "inningsDetails").FirstOrDefault() != null && f.InnerText == "Total").FirstOrDefault().NextSibling.NextSibling.NextSibling.NextSibling.InnerText + "(" + overs + ")";
                        if (!PlayerList1.Contains(pd))
                            PlayerList1.Add(pd);
                    }
                    var Listofnodes1 = doc.DocumentNode.SelectNodes("//table [@id='inningsBat2'and @class='inningsTable']/following::table[1]/tr/td[1]").Where(p => p.Attributes.Where(l => l.Name == "class" && l.Value == "inningsDetails").FirstOrDefault() != null).Select(m => m).Where(f => f.InnerText.Contains("Did not bat"));
                    foreach (HtmlNode node in Listofnodes1)
                    {
                        foreach (string player in node.InnerText.Substring(node.InnerText.IndexOf("Did not bat") + ("Did not bat".Length)).Split(new string[] { ",\n" }, StringSplitOptions.None))
                        {
                            PlayersDidNotBat1.Add(HttpUtility.HtmlDecode(player));
                        }
                    }
                    foreach (string player in PlayersDidNotBat1)
                    {
                        PlayerDetails pd = new PlayerDetails();
                        pd.PlayerID = PlayerList1.Count + 1;
                        pd.PlayerName = player;
                        pd.PlayerStatus = "Did not bat";
                        pd.Runs = 0;
                        pd.Overs = 0;
                        pd.TeamExtras = doc.DocumentNode.SelectNodes("//table [@id='inningsBat2'and @class='inningsTable']/tr[@class='inningsRow']").Elements().Where(f => f.Name == "td" && f.Attributes.Where(j => j.Value == "inningsDetails").FirstOrDefault() != null && f.InnerText == "Extras").FirstOrDefault().NextSibling.NextSibling.InnerText;
                        string Check = doc.DocumentNode.SelectNodes("//table [@id='inningsBat2'and @class='inningsTable']/tr[@class='inningsRow']").Elements().Where(f => f.Name == "td" && f.Attributes.Where(j => j.Value == "inningsDetails").FirstOrDefault() != null && f.InnerText == "Total").FirstOrDefault().NextSibling.NextSibling.InnerText;
                        string overs = string.Empty;
                        string wickets = string.Empty;
                        if (!Check.Substring(0, Check.IndexOf(';')).Contains("all out"))
                        {
                            wickets = Check.Substring(1, Check.IndexOf(';')).Substring(0, Check.Substring(1, Check.IndexOf(';')).IndexOf("wickets"));
                            overs = Check.Substring(Check.IndexOf(';') + 1, (Check.IndexOf("overs") - (Check.IndexOf(';') + 1)) - 1);
                        }
                        else
                        {
                            wickets = "";
                            overs = Check.Substring(Check.IndexOf(';') + 1, (Check.IndexOf("overs") - (Check.IndexOf(';') + 1)) - 1);
                        }
                        if (!string.IsNullOrEmpty(wickets))
                            pd.TeamTotal = doc.DocumentNode.SelectNodes("//table [@id='inningsBat2'and @class='inningsTable']/tr[@class='inningsRow']").Elements().Where(f => f.Name == "td" && f.Attributes.Where(j => j.Value == "inningsDetails").FirstOrDefault() != null && f.InnerText == "Total").FirstOrDefault().NextSibling.NextSibling.NextSibling.NextSibling.InnerText + "/" + wickets + "(" + overs + ")";
                        else
                            pd.TeamTotal = doc.DocumentNode.SelectNodes("//table [@id='inningsBat2'and @class='inningsTable']/tr[@class='inningsRow']").Elements().Where(f => f.Name == "td" && f.Attributes.Where(j => j.Value == "inningsDetails").FirstOrDefault() != null && f.InnerText == "Total").FirstOrDefault().NextSibling.NextSibling.NextSibling.NextSibling.InnerText + "(" + overs + ")";
                        if (!PlayerList1.Contains(pd))
                            PlayerList1.Add(pd);
                    }

                    teamBinnings = doc.DocumentNode.SelectSingleNode("//table [@id='inningsBat2'and @class='inningsTable']/tr[@class='inningsHead']/td[2]").InnerText;
                    teamBinnings = teamBinnings.Substring(0, teamBinnings.IndexOf("innings") - 1).Trim();
                    foreach (PlayerDetails ss in PlayerList1.ToList())
                    {
                        if (!DicForPlayernames.ContainsKey(ss.PlayerName))
                            DicForPlayernames.Add(ss.PlayerName, teamBinnings);
                    }
                    BowlerList = new ObservableCollection<BowlerDetails>();

                    List<string> PlayerNamesList3 = new List<string>();
                    List<string> PlayerOversList = new List<string>();
                    List<string> PlayerRunsList = new List<string>();
                    List<string> PlayerMaidensList = new List<string>();
                    List<string> PlayerWicketsList = new List<string>();

                    PlayerNamesList3 = doc.DocumentNode.SelectNodes("//table [@id='inningsBowl1'and @class='inningsTable']/tr[@class='inningsRow']/td[@class='playerName']").Select(i => i.InnerText).ToList();
                    PlayerOversList = doc.DocumentNode.SelectNodes("//table [@id='inningsBowl1'and @class='inningsTable']/tr[@class='inningsRow']/td[@class='bowlingDetails'][1]").Select(i => i.InnerText).ToList();
                    PlayerRunsList = doc.DocumentNode.SelectNodes("//table [@id='inningsBowl1'and @class='inningsTable']/tr[@class='inningsRow']/td[@class='bowlingDetails'][3]").Select(i => i.InnerText).ToList();
                    PlayerMaidensList = doc.DocumentNode.SelectNodes("//table [@id='inningsBowl1'and @class='inningsTable']/tr[@class='inningsRow']/td[@class='bowlingDetails'][2]").Select(i => i.InnerText).ToList();
                    PlayerWicketsList = doc.DocumentNode.SelectNodes("//table [@id='inningsBowl1'and @class='inningsTable']/tr[@class='inningsRow']/td[@class='bowlingDetails'][4]").Select(i => i.InnerText).ToList();
                    for (int c = 0; c < PlayerNamesList3.Count; c++)
                    {
                        BowlerDetails bd = new BowlerDetails();
                        if (c == 0)
                            bd.InningsHead = doc.DocumentNode.SelectSingleNode("//table [@id='inningsBowl1'and @class='inningsTable']/tr[@class='inningsHead']/td[2]").InnerText;
                        bd.PlayerID = BowlerList.Count + 1;
                        bd.PlayerName = PlayerNamesList3[c].ToString();
                        bd.Overs = Convert.ToDouble(PlayerOversList[c].ToString());
                        bd.Runs = Convert.ToInt32(PlayerRunsList[c].ToString());
                        bd.Maidens = Convert.ToInt32(PlayerMaidensList[c].ToString());
                        bd.Wickets = Convert.ToInt32(PlayerWicketsList[c].ToString());
                        if (!BowlerList.Contains(bd))
                            BowlerList.Add(bd);
                    }
                    BowlerList1 = new ObservableCollection<BowlerDetails>();

                    List<string> PlayerNamesList4 = new List<string>();
                    List<string> PlayerOversList1 = new List<string>();
                    List<string> PlayerRunsList1 = new List<string>();
                    List<string> PlayerMaidensList1 = new List<string>();
                    List<string> PlayerWicketsList1 = new List<string>();

                    PlayerNamesList4 = doc.DocumentNode.SelectNodes("//table [@id='inningsBowl2'and @class='inningsTable']/tr[@class='inningsRow']/td[@class='playerName']").Select(i => i.InnerText).ToList();
                    PlayerOversList1 = doc.DocumentNode.SelectNodes("//table [@id='inningsBowl2'and @class='inningsTable']/tr[@class='inningsRow']/td[@class='bowlingDetails'][1]").Select(i => i.InnerText).ToList();
                    PlayerRunsList1 = doc.DocumentNode.SelectNodes("//table [@id='inningsBowl2'and @class='inningsTable']/tr[@class='inningsRow']/td[@class='bowlingDetails'][3]").Select(i => i.InnerText).ToList();
                    PlayerMaidensList1 = doc.DocumentNode.SelectNodes("//table [@id='inningsBowl2'and @class='inningsTable']/tr[@class='inningsRow']/td[@class='bowlingDetails'][2]").Select(i => i.InnerText).ToList();
                    PlayerWicketsList1 = doc.DocumentNode.SelectNodes("//table [@id='inningsBowl2'and @class='inningsTable']/tr[@class='inningsRow']/td[@class='bowlingDetails'][4]").Select(i => i.InnerText).ToList();
                    for (int c = 0; c < PlayerNamesList4.Count; c++)
                    {
                        BowlerDetails bd = new BowlerDetails();
                        if (c == 0)
                            bd.InningsHead = doc.DocumentNode.SelectSingleNode("//table [@id='inningsBowl2'and @class='inningsTable']/tr[@class='inningsHead']/td[2]").InnerText;
                        bd.PlayerID = BowlerList1.Count + 1;
                        bd.PlayerName = PlayerNamesList4[c].ToString();
                        bd.Overs = Convert.ToDouble(PlayerOversList1[c].ToString());
                        bd.Runs = Convert.ToInt32(PlayerRunsList1[c].ToString());
                        bd.Maidens = Convert.ToInt32(PlayerMaidensList1[c].ToString());
                        bd.Wickets = Convert.ToInt32(PlayerWicketsList1[c].ToString());
                        if (!BowlerList1.Contains(bd))
                            BowlerList1.Add(bd);
                    }

                    savedataintodatabase(PlayerList, PlayerList1, BowlerList, BowlerList1);
                }
                getdatabtn.IsEnabled = true;
            }
            catch (Exception ex)
            {

                MessageBoxResult result = MessageBox.Show("Scorecard not yet available", "", MessageBoxButton.OK);
                if (result == MessageBoxResult.OK)
                {
                    NavigationService.GoBack();
                }
            }
        }
        public void savedataintodatabase(ObservableCollection<PlayerDetails> PlayerList, ObservableCollection<PlayerDetails> PlayerList1, ObservableCollection<BowlerDetails> BowlerList, ObservableCollection<BowlerDetails> BowlerList1)
        {
            try
            {
                string[] TeamA = default(string[]);
                string[] TeamB = default(string[]);
                string TeamAInnings = string.Empty;
                string TeamBInnings = string.Empty;
                string TeamResult = string.Empty;
                string MatchTitle = string.Empty;

                InsertBatting(PlayerList, "TeamABatting", out TeamA);

                InsertBatting(PlayerList1, "TeamBBatting", out TeamB);

                InsertBowling(BowlerList, "TeamBBowling");

                InsertBowling(BowlerList1, "TeamABowling");
                TeamAInnings = teamAinnings;
                TeamBInnings = teamBinnings;
                TeamResult = matchresult;
                InsertData<MatchExtras> insert = new InsertData<MatchExtras>();
                insert.ParameterList = new MatchExtras();
                insert.ParameterList.MatchID = AppSettings.ShowUniqueID;
                insert.ParameterList.TeamAExtras = TeamA[0].ToString();
                insert.ParameterList.TeamBExtras = TeamB[0].ToString();
                insert.ParameterList.TeamATotal = TeamA[1].ToString();
                insert.ParameterList.TeamBTotal = TeamB[1].ToString();
                insert.ParameterList.TeamAInnings = TeamAInnings;
                insert.ParameterList.TeamBInnings = TeamBInnings;
                insert.ParameterList.TeamResult = TeamResult;
                insert.ParameterList.ShowID = AppSettings.ShowUniqueID;
                insert.Insert();
                if (Dic.Keys.Count == 0)
                {

                    var cat = Constants.connection.Table<ShowCategories>().ToListAsync().Result.Select(i => new Properties { CategoryName = i.CategoryName, CategoryID = i.CategoryID }).ToList();
                    foreach (var list in cat)
                    {
                        if (!Dic.ContainsKey(list.CategoryName))
                            Dic.Add(list.CategoryName, list.CategoryID);
                    }

                }
                if (Dic.ContainsKey(teamAinnings))
                {
                    InsertData<CategoriesByShowID> insert3 = new InsertData<CategoriesByShowID>();
                    insert3.ParameterList = new CategoriesByShowID();
                    insert3.ParameterList.ShowID = AppSettings.ShowUniqueID;
                    insert3.ParameterList.CatageoryID = Dic.Where(i => i.Key == teamAinnings).FirstOrDefault().Value;
                    insert3.Insert();

                }
                else
                {
                    InsertData<ShowCategories> insert3 = new InsertData<ShowCategories>();
                    insert3.ParameterList = new ShowCategories();
                    insert3.ParameterList.CategoryID = Task.Run(async () => await Constants.connection.Table<ShowCategories>().OrderByDescending(i => i.CategoryID).FirstOrDefaultAsync()).Result.CategoryID + 1;
                    insert3.ParameterList.CategoryName = teamAinnings;
                    insert3.ParameterList.Abbreviation = teamAinnings.Substring(0, 3).ToUpper();
                    insert3.Insert();
                    InsertData<CategoriesByShowID> insert4 = new InsertData<CategoriesByShowID>();
                    insert4.ParameterList = new CategoriesByShowID();
                    insert4.ParameterList.ShowID = AppSettings.ShowUniqueID;
                    insert4.ParameterList.CatageoryID = insert3.ParameterList.CategoryID;
                    insert4.Insert();


                }
                if (Dic.ContainsKey(teamBinnings))
                {
                    InsertData<CategoriesByShowID> insert3 = new InsertData<CategoriesByShowID>();
                    insert3.ParameterList = new CategoriesByShowID();
                    insert3.ParameterList.ShowID = AppSettings.ShowUniqueID;
                    insert3.ParameterList.CatageoryID = Dic.Where(i => i.Key == teamBinnings).FirstOrDefault().Value;
                    insert3.Insert();

                }
                else
                {
                    InsertData<ShowCategories> insert3 = new InsertData<ShowCategories>();
                    insert3.ParameterList = new ShowCategories();
                    insert3.ParameterList.CategoryID = Task.Run(async () => await Constants.connection.Table<ShowCategories>().OrderByDescending(i => i.CategoryID).FirstOrDefaultAsync()).Result.CategoryID + 1;
                    insert3.ParameterList.CategoryName = teamBinnings;
                    insert3.ParameterList.Abbreviation = teamBinnings.Substring(0, 3).ToUpper();
                    insert3.Insert();
                    InsertData<CategoriesByShowID> insert4 = new InsertData<CategoriesByShowID>();
                    insert4.ParameterList = new CategoriesByShowID();
                    insert4.ParameterList.ShowID = AppSettings.ShowUniqueID;
                    insert4.ParameterList.CatageoryID = insert3.ParameterList.CategoryID;
                    insert4.Insert();

                }

                int showid = AppSettings.ShowUniqueID;

                List<ShowCast> castA = null;
                List<ShowCast> castB = null;
                int teamAcatid = Task.Run(async () => await Constants.connection.Table<ShowCategories>().Where(i => i.CategoryName == teamAinnings).FirstOrDefaultAsync()).Result.CategoryID;
                int teamBcatid = Task.Run(async () => await Constants.connection.Table<ShowCategories>().Where(i => i.CategoryName == teamBinnings).FirstOrDefaultAsync()).Result.CategoryID;
                foreach (KeyValuePair<string, string> data in DicForPlayernames.Where(i => i.Value == teamAinnings))
                {
                    List<CastProfile> CastProfilepersonid = Task.Run(async () => await Constants.connection.Table<CastProfile>().Where(i => i.Name == data.Key).ToListAsync()).Result;
                    foreach (CastProfile pro in CastProfilepersonid)
                    {
                        castA = Task.Run(async () => await Constants.connection.Table<ShowCast>().Where(i => i.ShowID == showid && i.PersonID == pro.PersonID).ToListAsync()).Result;
                    }

                    foreach (var dd in castA)
                    {
                        ShowCast cast1 = dd;
                        cast1.CategoryID = teamAcatid;
                        Constants.connection.UpdateAsync(cast1);

                    }
                }
                foreach (KeyValuePair<string, string> data in DicForPlayernames.Where(i => i.Value == teamBinnings))
                {
                    List<CastProfile> CastProfilepersonidB = Task.Run(async () => await Constants.connection.Table<CastProfile>().Where(i => i.Name == data.Key).ToListAsync()).Result;
                    foreach (CastProfile pro in CastProfilepersonidB)
                    {
                        castB = Task.Run(async () => await Constants.connection.Table<ShowCast>().Where(i => i.ShowID == showid && i.PersonID == pro.PersonID).ToListAsync()).Result;
                    }
                    foreach (var dd in castB)
                    {
                        ShowCast cast1 = dd;
                        cast1.CategoryID = teamBcatid;
                        Constants.connection.UpdateAsync(cast1);
                    }
                }
                NavigationService.GoBack();
            }
            catch (Exception ex)
            {
                
             
            }
        }
        private static void InsertBatting(ObservableCollection<PlayerDetails> BattingList, string TeamType, out string[] Team)
        {
           
                int showid = AppSettings.ShowUniqueID;
                Team = new string[2];
                Team[0] = string.Empty;
                Team[1] = string.Empty;

                try
                {
                    foreach (PlayerDetails BI in BattingList)
                    {
                        int PlayerId = 0;
                        string PlayerName = BI.PlayerName;
                        string PlayerBalls = BI.Overs.ToString();
                        Team[0] = BI.TeamExtras;
                        Team[1] = BI.TeamTotal;
                        if (Task.Run(async () => await Constants.connection.Table<CastProfile>().Where(i => i.Name == PlayerName).FirstOrDefaultAsync()).Result != null)
                            PlayerId = Task.Run(async () => await Constants.connection.Table<CastProfile>().Where(i => i.Name == PlayerName).FirstOrDefaultAsync()).Result.PersonID;

                        if (PlayerId == 0)
                        {
                            int minpersonid = AppSettings.MinPersonID;
                            if (Task.Run(async () => await Constants.connection.Table<CastProfile>().Where(i => i.PersonID < minpersonid).OrderByDescending(i => i.PersonID).FirstOrDefaultAsync()).Result != null)
                                PlayerId = Task.Run(async () => await Constants.connection.Table<CastProfile>().Where(i => i.PersonID < minpersonid).OrderByDescending(i => i.PersonID).FirstOrDefaultAsync()).Result.PersonID + 1;
                            else
                                PlayerId = 2;
                            InsertData<CastProfile> insert1 = new InsertData<CastProfile>();
                            insert1.ParameterList = new CastProfile();
                            insert1.ParameterList.Name = PlayerName;
                            insert1.ParameterList.PersonID = PlayerId;
                            insert1.Insert();
                        }
                        var res = Task.Run(async () => await Constants.connection.Table<CastProfile>().Where(i => i.Name == PlayerName).ToListAsync()).Result;
                        foreach (CastProfile hn in res)
                        {
                            var fg = Task.Run(async () => await Constants.connection.Table<ShowCast>().Where(i => i.ShowID == showid && i.PersonID == hn.PersonID).FirstOrDefaultAsync()).Result;
                            if (fg != null)
                            {

                            }
                            else
                            {
                                InsertData<ShowCast> insert = new InsertData<ShowCast>();
                                insert.ParameterList = new ShowCast();
                                insert.ParameterList.ShowID = AppSettings.ShowUniqueID;
                                insert.ParameterList.PersonID = PlayerId;
                                // insert.ParameterList.RoleID = 5;
                                insert.ParameterList.CategoryID = 0;
                                insert.Insert();
                            }
                        }
                        InsertData<MatchBattingScore> insert2 = new InsertData<MatchBattingScore>();
                        insert2.ParameterList = new MatchBattingScore();
                        insert2.ParameterList.MatchId = AppSettings.ShowUniqueID;
                        insert2.ParameterList.PlayerName = PlayerName;
                        insert2.ParameterList.PlayerID = PlayerId.ToString();
                        insert2.ParameterList.TeamType = TeamType;
                        insert2.ParameterList.Balls = (PlayerBalls.Contains('(') ? PlayerBalls : "(" + PlayerBalls + ")");
                        insert2.ParameterList.Runs = BI.Runs;
                        insert2.ParameterList.Out = BI.PlayerStatus;
                        insert2.Insert();

                    }
                }
                catch (Exception ex)
                {
                    
                  
                }

           
        }
        private static void InsertBowling(ObservableCollection<BowlerDetails> BowlingList, string TeamType)
        {
            try
            {
                int showid = AppSettings.ShowUniqueID;
                foreach (BowlerDetails BI in BowlingList)
                {
                    int PlayerId = 0;
                    string PlayerName = BI.PlayerName;
                    string PlayerOvers = BI.Overs.ToString();
                    if (Task.Run(async () => await Constants.connection.Table<CastProfile>().Where(i => i.Name == PlayerName).FirstOrDefaultAsync()).Result != null)
                        PlayerId = Task.Run(async () => await Constants.connection.Table<CastProfile>().Where(i => i.Name == PlayerName).FirstOrDefaultAsync()).Result.PersonID;

                    InsertData<MatchBowlingScore> insert3 = new InsertData<MatchBowlingScore>();
                    insert3.ParameterList = new MatchBowlingScore();
                    insert3.ParameterList.MatchId = AppSettings.ShowUniqueID;
                    insert3.ParameterList.PlayerID = PlayerId.ToString();
                    insert3.ParameterList.Overs = float.Parse(PlayerOvers, CultureInfo.InvariantCulture.NumberFormat);
                    insert3.ParameterList.Runs = BI.Runs;
                    insert3.ParameterList.Maidens = BI.Maidens;
                    insert3.ParameterList.Wickets = BI.Wickets;
                    insert3.ParameterList.PlayerName = PlayerName;
                    insert3.ParameterList.TeamType = TeamType;
                    insert3.Insert();


                }
            }
            catch (Exception ex)
            {
                
                
            }
        }

        private void TextBlock_Loaded_1(object sender, RoutedEventArgs e)
        {
            TextBlock tb = sender as TextBlock;
            if (tb.Text.Contains("Choose Category"))
            {
                tb.Visibility = Visibility.Collapsed;
                tb.Loaded -= TextBlock_Loaded_1;
            }
        }
    }
}